package com.dtda.edu.miaosha.common;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;



/**
 * @author 袁强
 * @version 2019年2月18日 下午6:04:34
 * 类说明  
 */
public class ValidatorUtil {
	
	//通过工厂创建校验 Validator 实例化
	private static Validator validator = (Validator) Validation.buildDefaultValidatorFactory()
            .getValidator();

	public static ValidatorImpl validate(Object obj){
		ValidatorImpl validatorImpl = new ValidatorImpl();
        Set<ConstraintViolation<Object>> set = validator.validate(obj,Default.class);
        if(set != null && set.size() >0 ){
        	validatorImpl.isHasError = true;
        	String property = null;   //错误字段
        	String errorMsg = null;   //错误字段的错误描述信息
            for(ConstraintViolation<Object> cv : set){
            	 property = cv.getPropertyPath().toString();   //获取错误字段
                 errorMsg = cv.getMessage();   //获取错误字段的描述信息
                 validatorImpl.getErrorMap().put(property, errorMsg);
            }
        }
        return validatorImpl;
    }
}
